package com.climber.android.lib_share.sensor

import android.os.Handler
import android.os.Looper
import android.util.Log
import cn.sharesdk.framework.Platform
import cn.sharesdk.framework.PlatformActionListener
import cn.sharesdk.wechat.friends.Wechat
import com.climber.android.lib_share.OneShare
import java.util.HashMap


/**
 * Created by Mikes at 2020-03-20 09:35
 */
class MyAuthorizeActionListener(private val builderTT: AuthorizeResultCallBack.Builder.() -> Unit) : PlatformActionListener{
    private val mainHandler : Handler = Handler(Looper.getMainLooper())
    private var authorizeResultCallBack : AuthorizeResultCallBack?=null
    init {
        authorizeResultCallBack = AuthorizeResultCallBack().apply { registerListener(builderTT) }
    }

    override fun onComplete(platform: Platform, p1: Int, value: HashMap<String, Any>?) {
        val info = StringBuilder()
        // 不同平台都会缓存accessToken、expiresIn、UserId、nickname 等信息
        info.append("accessToken : " + platform.db.token + "\n")                          // accessToken, 获取授权token
                .append("expiresTime : " + platform.db.expiresTime + "\n")                  // 授权Token的有效时间
                .append("UserId : " + platform.db.userId + "\n")                     // 获取用户在此平台的ID
                .append("nickname : " + platform.db.userName + "\n")                   // 获取用户昵称

        if(platform.name == Wechat.NAME){
            info.append("wechat unionid : " + platform.db.get("unionid") + "\n")           // 微信unionid字段
        }
        Log.d(OneShare.TAG, info.toString())

        Log.d(OneShare.TAG, "${platform.name} login success, value : ${value?.toString()}")

        val authorizaInfo = mutableMapOf<String, Any>()
        authorizaInfo.putAll(value ?: emptyMap())
        authorizaInfo["cc_access_token"] = platform.db.token
        authorizaInfo["cc_expire_time"] = platform.db.expiresTime.toString()
        authorizaInfo["cc_nickname"] = platform.db.userName
        authorizaInfo["cc_user_id"] = platform.db.userId
        if(platform.name == Wechat.NAME){
            authorizaInfo["cc_unionid"] = platform.db.get("unionid")
        }

        mainHandler.post {
            authorizeResultCallBack?.builder?.success?.invoke(authorizaInfo)
        }
    }

    override fun onCancel(platform: Platform, code: Int) {
        Log.d(OneShare.TAG, "${platform.name} login canceled, cancelCode : $code ")
        mainHandler.post {
            authorizeResultCallBack?.builder?.cancel?.invoke()
        }
    }

    override fun onError(platform: Platform, code: Int, throwable: Throwable?) {
        Log.d(OneShare.TAG, "${platform.name} login error, errorCode : $code, cause by ${Log.getStackTraceString(throwable)}")
        mainHandler.post {
            authorizeResultCallBack?.builder?.error?.invoke()
        }
    }
}